package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备表Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备表
     * 
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备表列表
     * 
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        //修改Iot上面的信息
        UpdateDeviceRequest deviceName=new UpdateDeviceRequest();
        deviceName.setDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.setDeviceName(device.getDeviceName());
        deviceName.setBody(body);
        UpdateDeviceResponse updateDeviceResponse = client.updateDevice(deviceName);
        if (updateDeviceResponse.getHttpStatusCode()!=200){
            throw new RuntimeException("修改设备名称失败");
        }
        //1.判断设备是否已经注册（设备名称是否存在）v
       /* long count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, device.getDeviceName()));
        if (count>0) {
            throw new RuntimeException("设备名称已存在");
        }*/
        //3.判断同一位置是否绑定相同的产品
        long count = this.count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, device.getProductKey())
                .eq(Device::getBindingLocation, device.getBindingLocation())
                .eq(Device::getLocationType, device.getLocationType())
                .eq(device.getPhysicalLocationType()!=null,Device::getPhysicalLocationType, device.getPhysicalLocationType())
        );
        if (count>0) {
            throw new RuntimeException("同一位置只能绑定一个相同产品");
        }

        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备表
     * 
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备表信息
     * 
     * @param id 设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置条数
        listProductsRequest.setLimit(50);
        //发起请求
        ListProductsResponse listProductsResponse = client.listProducts(listProductsRequest);
        if(listProductsResponse.getHttpStatusCode()!=200){
            throw new RuntimeException("同步产品列表失败");
        }
        //将结果存储到redis中
        redisTemplate.opsForValue().set(Constants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(listProductsResponse.getProducts()));

    }

    /**
     * 获取所有产品列表
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //从redis中获取所有产品列表
        String productList = (String) redisTemplate.opsForValue().get(Constants.IOT_ALL_PRODUCT_LIST);
        //如果数据为空，则返回
        if(StringUtils.isEmpty(productList)){
            return Collections.emptyList();
        }
        //解析数据并转换为ProductVo对象，返回
        return JSONUtil.toList(productList, ProductVo.class);
    }

    /**
     * 注册设备
     * @param dto
     */
    @Override
    public void registerDevice(DeviceDto dto) {
        //1.判断设备是否已经注册（设备名称是否存在）
        long count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()));
        if (count>0) {
            throw new RuntimeException("设备名称已存在");
        }

        //2.判断设备标识是否存在
        count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId()));
        if (count>0) {
            throw new RuntimeException("设备标识已存在");
        }

        //3.判断同一位置是否绑定相同的产品
        count = this.count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(dto.getPhysicalLocationType()!=null,Device::getPhysicalLocationType, dto.getPhysicalLocationType())
        );
        if (count>0) {
            throw new RuntimeException("同一位置只能绑定一个相同产品");
        }

        //4.注册设备到Iot平台
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body=new AddDevice();
        body.setDeviceName(dto.getDeviceName());
        body.setProductId(dto.getProductKey());
        body.setNodeId(dto.getNodeId());
        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replace("-", "");
        authInfo.setSecret(secret);
        body.setAuthInfo(authInfo);
        request.setBody(body);
        AddDeviceResponse addDeviceResponse = client.addDevice(request);
        if(addDeviceResponse.getHttpStatusCode()!=201){
            throw new RuntimeException("设备注册失败");
        }
        //5.保存设备到本地数据库
        Device bean = BeanUtil.toBean(dto, Device.class);
        bean.setIotId(addDeviceResponse.getDeviceId());
        bean.setSecret(secret);
        this.save(bean);

    }

    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查询本地设备数据
        Device one = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(one)){
            throw new RuntimeException("设备不存在");
        }
        //根据产品和设备查询设备详情
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse showDeviceResponse = client.showDevice(request);
        if (showDeviceResponse.getHttpStatusCode()!=200){
            throw new RuntimeException("查询设备详情失败");
        }
        //封装数据并返回
        DeviceDetailVo bean = BeanUtil.toBean(one, DeviceDetailVo.class);
        bean.setDeviceStatus(showDeviceResponse.getStatus());
        //日期转换
        String activeTime = showDeviceResponse.getActiveTime();
        if (StringUtils.isNotEmpty(activeTime)){
            LocalDateTime parse = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
            LocalDateTime localDateTime = DateTimeZoneConverter.utcToShanghai(parse);
            bean.setActiveTime(localDateTime);
        }

        return bean;


    }

    /**
     * 查询设备服务属性
     * @param iotId
     * @return
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        //根据设备ID查询设备服务属性
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse showDeviceShadowResponse = client.showDeviceShadow(request);
        if (showDeviceShadowResponse.getHttpStatusCode()!=200){
            throw new RuntimeException("查询设备详情失败");
        }
        List<DeviceShadowData> shadow = showDeviceShadowResponse.getShadow();
        if (CollUtil.isEmpty(shadow)){
            return Collections.emptyList();
        }
        //获取上报数据的reported
        DeviceShadowProperties reported = shadow.get(0).getReported();
        List<Map<String, Object>> list = new ArrayList<>();
        //将数据转换成JSONObject（map）格式
        JSONObject parseObj = JSONUtil.parseObj(reported.getProperties());
        //日期转化
        String eventTime = reported.getEventTime();
        LocalDateTime  eventTimeL = LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
        //加时区
        final LocalDateTime time = DateTimeZoneConverter.utcToShanghai(eventTimeL);
        //遍历数据，封装到list集合中
        parseObj.forEach((key, value)->{
            Map<String, Object> map = new HashMap<>();
            map.put("functionId",key);
            map.put("value",value);
            map.put("eventTime",time);
            list.add(map);
        });

        return list;
    }

    /**
     * 删除设备
     * @param iotId
     */
    @Override
    public void deleteById(String iotId) {
        //从iot 平台删除设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        DeleteDeviceResponse deleteDeviceResponse = client.deleteDevice(request);
        if (deleteDeviceResponse.getHttpStatusCode()!=204){
            throw new RuntimeException("删除设备失败");
        }
        this.remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
    }

    /**
     * 查询产品列表详情
     * @return
     */
    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        if (StringUtils.isEmpty(productKey)){
            throw new RuntimeException("产品ID不能为空");
        }
        //调用Iot平台查询产品列表详情
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse showProductResponse = client.showProduct(request);
        if (showProductResponse.getHttpStatusCode()!=200){
            throw new RuntimeException("查询产品列表详情失败");
        }
        List<ServiceCapability> serviceCapabilities = showProductResponse.getServiceCapabilities();
        if (CollUtil.isNotEmpty(serviceCapabilities)){
            return serviceCapabilities;
        }

        return serviceCapabilities;
    }


}
